const express = require("express");
const fs = require("fs");
const app = express();
//中间件
app.use(express.static("./www"));

/* 
HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Thu, 04 Jan 2024 07:40:23 GMT
ETag: W/"2401d62-18cd36a8986"
Content-Type: video/mp4
Content-Length: 37756258
Date: Tue, 23 Jan 2024 08:55:03 GMT
Connection: keep-alive
Keep-Alive: timeout=5
*/
// 中间件 处理GET请求
app.use((req, res, next) => {
  if (req.method === "GET") {
    res.sendFile("f:/video/16-2.模式17.mp4");
  } else {
    next();
  }
});
// 中间件 处理POST请求
app.use((req, res, next) => {
  if (req.method === "POST") {
    fs.writeFile("./www/a.txt", "hello jack", (err) => {
      if (err === null) {
        res.send("hello POST success");
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});
// 中间件 处理PUT请求
app.use((req, res, next) => {
  if (req.method === "PUT") {
    fs.writeFile("./www/a.txt", "hello lili", (err) => {
      if (err === null) {
        res.send("hello PUT success");
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});
// 中间件 处理 DELETE 请求
app.use((req, res, next) => {
  if (req.method === "DELETE") {
    fs.unlink("./www/a.txt", (err) => {
      if (err === null) {
        res.send("hello DELETE success");
      } else {
        res.send(err.message);
      }
    });
  } else {
    next();
  }
});

// 设置端口
const port = 3009;
app.listen(port, () => {
  console.log(`http://192.168.1.42:${port}`);
});
